package Thread_;

public class Thread16 {
    //wait,notify
    public static void main(String[] args) throws InterruptedException {
        Object locker=new Object();
        Thread t1=new Thread(){
            @Override
            public void run() {
                synchronized(locker){
                    System.out.println("wait之前 ");
                    try {
                        locker.wait();//释放锁，并进入阻塞状态WAITING
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("wait之后 ");
                }
            }
        };
        Thread t2=new Thread(()->{
            try {
                Thread.sleep(1000);//先等t1线程获取到锁，执行到wait
                synchronized(locker){//t1已经释放了锁，t2获取到锁，
                    System.out.println("notify之前");
                    locker.notify();//唤醒t1的wait,
                                    //t1和t2共同竞争锁，由于t2此时是持有锁的，因此会先执行完t2的代码
                                    //再去执行t1
                    System.out.println("notify之后");
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t1.start();
        t2.start();
    }

    public static void main2(String[] args) throws InterruptedException {
        Object locker=new Object();
        new Thread(()->{
            System.out.println("Thread ");
            try {
                locker.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
        Thread.sleep(1000);
        locker.notify();
    }
}
